package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    //分页查询
    @Override
    public PageResult findPage(Integer pageNum, Integer sizeNum, String queryString) {
        //PageHelper.startPage(pageNum,sizeNum,String);第三个参数可以用来排序
        PageHelper.startPage(pageNum,sizeNum);
        Page<Permission> page = permissionDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }
    //新增权限
    @Override
    public void addPermission(Permission permission) {
        permission.setCreateontime(new Date());
        permissionDao.add(permission);
    }
    //编辑回显数据
    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }
    //编辑修改数据
    @Override
    public void updatePermission(Permission permission) {
        permissionDao.update(permission);
    }
    //删除廯数据
    @Override
    public void deletePermission(Integer id) {

        Integer ridByPid = permissionDao.findRidByPid(id);
        if (ridByPid>0){
            throw  new RuntimeException("删除失败，该权限被关联");
        }
        permissionDao.delete(id);
    }

    //查询所有权限
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    //查询角色关联的权限id
    @Override
    public Integer[] findPermissionIds(Integer id) {
        return permissionDao.findPermissionIds(id);
    }


    /**
     * 修改权限的状态
     * @param permissionId
     * @param status
     */
    @Override
    public void updateStatus(Integer permissionId, Integer status) {
        Map<String,Integer> map = new HashMap<>();
        map.put("permissionId",permissionId);
        map.put("status",status);
        permissionDao.updateStatus(map);
    }
}
